'use strict';
var entityCollection = require('../../../Base/server/controllers/EntityCollection'),
	roleController = require('../../../SystemManage/server/controllers/Role.server.controller');

/**
 * Module dependencies.
 */
var _ = require('lodash');

/**
 * Extend user's controller
 */
module.exports = _.extend(
    require('./users/users.authentication.server.controller'),
    require('./users/users.password.server.controller'),
    require('./users/users.profile.server.controller')
);

module.exports.getUserByID = function(id, completeFun){
	var userEntity = entityCollection.getEntity("User");
	userEntity.findById(id, null, function(err, userRecord){
		if(err){
			var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询用户信息错误';
            newErr.message = '查询失败，请检查查询参数！';
            completeFun(newErr);
		}
		else{
			completeFun(null, userRecord);
		}
	});
};

//根据用户ID获取用户信息以及角色信息
module.exports.getUserAndRolesInfo = function(id, completeFun){
	this.getUserByID(id, function(err, userRecord){
		if(err){
			completeFun(err);
		}
		else{
			if(userRecord == null){
				var newErr = new Error();
	            newErr.leval = 9;
	            newErr.title = '查询用户信息';
	            newErr.message = '当前ID没有对应的用户！';
	            completeFun(newErr);
			}
			else{
				roleController.getRolesByUser(userRecord, function(err, roleRecords){
					if(err){
						completeFun(err);
					}
					else{
						userRecord.Roles = roleRecords;
						var isQC = false;
			        	for(var i=0; i<roleRecords.length; i++){
			        		if(roleRecords[i].Code == "QC"){
			        			isQC = true;
					            break;
			        		}
			        	}
			        	userRecord._doc.IsQC = isQC;
			        	completeFun(null, userRecord);
					}
				});
			}
		}
	});
};

//根据用户ID获取用户信息
module.exports.getUserInfo = function (id, completeFun) {
	var userEntity = entityCollection.getEntity("User");
	userEntity.Entity
	.findOne({_id: id}, {Code: 1, Name: 1, Image: 1, Roles: 1})
	.populate({ path: 'Roles', select: 'Code Name' })
	.exec(function (err, record) {
		if (err) {
		    completeFun(err);
		    return;
		}
		if (record == null) {
		    var newErr = new Error();
		    newErr.leval = 9;
		    newErr.title = '查找员工档失败';
		    newErr.message = '该条码没有对应的员工信息！';
		    completeFun(newErr);
		    return;
		}
		completeFun(null, record);
	});
};